<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Conf_contr extends CI_Controller {

	private $users = array();

	public function __construct() {
		parent::__construct();
	  	$usersId = array('40022', '180047', '1846670', '1846624', '40034', '40040');
	  	$this->users = $this->Conf_model->get_users_list($usersId);
	}

	public function index() {
		foreach ($this->users as $tmp) {
			$data['users'][$tmp['perId']] = $tmp['FIO'];
		}
		$this->load->view('conf_forms/login', $data);
	}
	
	private function format_users_array($type) {
		switch ($type) {
			case 1:
				foreach ($this->users as $tmp) {
					$arr[$tmp['perId']] = $tmp['mptext'];
				}				
			break;
			case 2:
				foreach ($this->users as $tmp) {
					$arr[$tmp['perId']] = $tmp['FIO'];
				}				
			break;
		}
		return $arr;
	}
	
	public function check_login() {
		$perId = $this->input->post('userId');
		$perPass = $this->input->post('pass');
		$passHash = md5($perPass);
		$arr = $this->format_users_array(1);
		if ($passHash == $arr[$perId]) {
			$this->session;
			$arr1 = $this->format_users_array(2);
			$this->session->set_userdata(array('userName' => $arr1[$perId]));
			$data['userName'] = $this->session->userdata('userName');
			$data['prevConf'] = $this->Conf_model->get_xml_configuration();
			$data['subjects'] = $this->Conf_model->get_subjects_list();
			$this->load->view('conf_forms/conf_main', $data); 
		} else {
			$data['text'] = 'Невірний паролько користувача!';
			foreach ($this->users as $tmp) {
				$data['users'][$tmp['perId']] = $tmp['FIO'];
			}
			$this->load->view('conf_forms/login', $data);			
		}
	}
	
	public function check_conf() {
		if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
			$type = $this->input->post('type', TRUE);
			switch ($type) {
				case '1':
					$saId = '6521B186-3E2B-441d-A09A-D0B5F47534B7';
					$date[] = $this->input->post('date1', TRUE);
					$date[] = $this->input->post('date2', TRUE);
					foreach ($_POST['day1'] as $tmp) {
						$days[$date[0]][] = $tmp;
					}
					foreach ($_POST['day2'] as $tmp) {
						$days[$date[1]][] = $tmp;
					}
					print_r($days);
					$this->Conf_model->save_prob_conf($days, $saId);
				break;
				case '2':
					$saId = '8006FC48-691A-4438-8176-AAAE9BCC90DB';
					print_r($_POST);
					for ($i=1; $i <= 13; $i++) { 
						$date = $this->input->post("date$i", TRUE);
						$subj = $this->input->post("subj$i", TRUE);
						$sesNum = $this->input->post("sesNum$i", TRUE);
						$data[] = "$subj;$sesNum:$date";
					}
					print_r($data);
					$this->Conf_model->save_osn_conf($data, $saId);
				break;
			}
		}
	}
	
	public function stat_exit() {
		$this->session->sess_destroy();
		redirect('/conf', 'refresh');
	}
}